<template>
  <v-card>
    <v-card-title class="d-flex align-center justify-space-between">
      <span>{{ title }}</span>
      <v-btn color="primary" @click="refreshList">
        <v-icon>mdi-refresh</v-icon>
        刷新
      </v-btn>
    </v-card-title>

    <!-- 搜索筛选区域 -->
    <v-card-text>
      <v-row>
        <v-col cols="12" md="3">
          <v-text-field
            v-model="searchParams.taskName_LIKE"
            label="任务名称"
            placeholder="请输入任务名称关键词"
            clearable
            variant="outlined"
            density="compact"
          />
        </v-col>
        <v-col cols="12" md="3">
          <v-select
            v-model="searchParams.status_EQ"
            :items="statusOptions"
            label="状态"
            clearable
            variant="outlined"
            density="compact"
          />
        </v-col>
        <v-col cols="12" md="3">
          <v-text-field
            v-model="searchParams.assignee_EQ"
            label="审批人"
            placeholder="请输入审批人ID"
            clearable
            variant="outlined"
            density="compact"
          />
        </v-col>
        <v-col cols="12" md="3">
          <v-btn color="primary" @click="handleSearch" class="mr-2">
            <v-icon>mdi-magnify</v-icon>
            搜索
          </v-btn>
          <v-btn variant="outlined" @click="resetSearch">
            <v-icon>mdi-refresh</v-icon>
            重置
          </v-btn>
        </v-col>
      </v-row>
    </v-card-text>

    <!-- 数据表格 -->
    <v-data-table-server
      v-model:items-per-page="pageSize"
      v-model:page="currentPage"
      :headers="headers"
      :items="tasks"
      :items-length="total"
      :loading="loading"
      item-value="id"
      @update:options="loadTasks"
    >
      <!-- 任务名称列 -->
      <template v-slot:item.taskName="{ item }">
        <div>
          <div class="text-body-2 font-weight-medium">{{ item.taskName }}</div>
          <div class="text-caption text-grey">{{ item.instanceId }}</div>
        </div>
      </template>

      <!-- 审批人列 -->
      <template v-slot:item.assignee="{ item }">
        <div v-if="item.assigneeName" class="d-flex align-center">
          <v-avatar size="24" class="mr-2" color="primary">
            <span class="text-white font-weight-bold text-caption">
              {{ item.assigneeName.charAt(0) }}
            </span>
          </v-avatar>
          <span class="text-body-2">{{ item.assigneeName }}</span>
        </div>
        <div v-else-if="item.candidateUsers || item.candidateGroups" class="text-caption text-grey">
          候选人/组
        </div>
        <div v-else class="text-caption text-grey">未分配</div>
      </template>

      <!-- 状态列 -->
      <template v-slot:item.status="{ item }">
        <v-chip
          :color="getStatusColor(item.status)"
          size="small"
          variant="tonal"
        >
          {{ getStatusText(item.status) }}
        </v-chip>
      </template>

      <!-- 创建时间列 -->
      <template v-slot:item.createTime="{ item }">
        {{ formatDate(item.createTime) }}
      </template>

      <!-- 处理时间列 -->
      <template v-slot:item.processTime="{ item }">
        {{ item.processTime ? formatDate(item.processTime) : '-' }}
      </template>

      <!-- 超时时间列 -->
      <template v-slot:item.dueDate="{ item }">
        <div v-if="item.dueDate">
          <span :class="isOverdue(item.dueDate) ? 'text-error' : ''">
            {{ formatDate(item.dueDate) }}
          </span>
          <v-icon v-if="isOverdue(item.dueDate)" color="error" size="small" class="ml-1">
            mdi-clock-alert
          </v-icon>
        </div>
        <span v-else>-</span>
      </template>

      <!-- 操作列 -->
      <template v-slot:item.actions="{ item }">
        <div class="d-flex gap-2">
          <!-- 查看详情 -->
          <v-btn
            size="small"
            color="primary"
            variant="text"
            @click="viewDetail(item)"
          >
            <v-icon>mdi-eye</v-icon>
            查看
          </v-btn>

          <!-- 审批操作 -->
          <template v-if="item.status === 'PENDING' && canProcess(item)">
            <v-btn
              size="small"
              color="success"
              variant="text"
              @click="processTask(item, 'APPROVE')"
            >
              <v-icon>mdi-check</v-icon>
              通过
            </v-btn>
            <v-btn
              size="small"
              color="error"
              variant="text"
              @click="processTask(item, 'REJECT')"
            >
              <v-icon>mdi-close</v-icon>
              拒绝
            </v-btn>
          </template>

          <!-- 认领 -->
          <v-btn
            v-if="!item.assignee && canClaim(item)"
            size="small"
            color="info"
            variant="text"
            @click="claimTask(item)"
          >
            <v-icon>mdi-hand-back-left</v-icon>
            认领
          </v-btn>

          <!-- 更多操作 -->
          <v-menu v-if="item.status === 'PENDING' && item.assignee">
            <template v-slot:activator="{ props }">
              <v-btn
                size="small"
                variant="text"
                icon="mdi-dots-vertical"
                v-bind="props"
              />
            </template>
            <v-list>
              <v-list-item @click="delegateTask(item)">
                <v-list-item-title>委托</v-list-item-title>
              </v-list-item>
              <v-list-item @click="transferTask(item)">
                <v-list-item-title>转办</v-list-item-title>
              </v-list-item>
            </v-list>
          </v-menu>
        </div>
      </template>
    </v-data-table-server>
  </v-card>

  <!-- 任务处理弹窗 -->
  <ApprovalTaskProcess
    v-model="processDialog"
    :task="selectedTask"
    :action="processAction"
    @success="refreshList"
  />

  <!-- 任务详情弹窗 -->
  <ApprovalTaskDetail
    v-model="detailDialog"
    :task="selectedTask"
    @refresh="refreshList"
  />

  <!-- 委托弹窗 -->
  <ApprovalTaskDelegate
    v-model="delegateDialog"
    :task="selectedTask"
    @success="refreshList"
  />

  <!-- 转办弹窗 -->
  <ApprovalTaskTransfer
    v-model="transferDialog"
    :task="selectedTask"
    @success="refreshList"
  />
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { useMessage } from '@/composables/useMessage';
import { format, isPast } from 'date-fns';
import {
  getTaskList,
  getMyPendingTasks,
  getMyCompletedTasks,
  getCandidateTasks,
  claimTask as claimTaskApi,
  type ApprovalTaskModel,
  type ApprovalTaskQueryParams
} from '@/api/approval/task/ApprovalTaskApi';
import ApprovalTaskProcess from './ApprovalTaskProcess.vue';
import ApprovalTaskDetail from './ApprovalTaskDetail.vue';
import ApprovalTaskDelegate from './ApprovalTaskDelegate.vue';
import ApprovalTaskTransfer from './ApprovalTaskTransfer.vue';

// Props
interface Props {
  type?: 'all' | 'pending' | 'completed' | 'candidate';
  title?: string;
}

const props = withDefaults(defineProps<Props>(), {
  type: 'all',
  title: '审批任务列表',
});

// 组合式函数
const { success: showSuccess, error: showError } = useMessage();

// 响应式数据
const loading = ref(false);
const tasks = ref<ApprovalTaskModel[]>([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);

// 搜索参数
const searchParams = reactive<Partial<ApprovalTaskQueryParams>>({
  taskName_LIKE: '',
  status_EQ: '',
  assignee_EQ: '',
});

// 弹窗状态
const processDialog = ref(false);
const detailDialog = ref(false);
const delegateDialog = ref(false);
const transferDialog = ref(false);
const selectedTask = ref<ApprovalTaskModel | null>(null);
const processAction = ref<'APPROVE' | 'REJECT'>('APPROVE');

// 状态选项
const statusOptions = [
  { title: '待处理', value: 'PENDING' },
  { title: '已通过', value: 'APPROVED' },
  { title: '已拒绝', value: 'REJECTED' },
  { title: '已委托', value: 'DELEGATED' },
  { title: '已转办', value: 'TRANSFERRED' },
];

// 表格列定义
const headers = computed(() => {
  const baseHeaders = [
    { title: '任务名称', key: 'taskName', align: 'start' as const },
    { title: '审批人', key: 'assignee', align: 'center' as const },
    { title: '状态', key: 'status', align: 'center' as const },
    { title: '创建时间', key: 'createTime', align: 'center' as const },
  ];

  if (props.type === 'completed') {
    baseHeaders.push({ title: '处理时间', key: 'processTime', align: 'center' as const });
  } else {
    baseHeaders.push({ title: '超时时间', key: 'dueDate', align: 'center' as const });
  }

  baseHeaders.push({ title: '操作', key: 'actions', align: 'center' as const, sortable: false });
  return baseHeaders;
});

// 获取状态颜色
function getStatusColor(status: string): string {
  switch (status) {
    case 'PENDING':
      return 'warning';
    case 'APPROVED':
      return 'success';
    case 'REJECTED':
      return 'error';
    case 'DELEGATED':
      return 'info';
    case 'TRANSFERRED':
      return 'purple';
    default:
      return 'grey';
  }
}

// 获取状态文本
function getStatusText(status: string): string {
  switch (status) {
    case 'PENDING':
      return '待处理';
    case 'APPROVED':
      return '已通过';
    case 'REJECTED':
      return '已拒绝';
    case 'DELEGATED':
      return '已委托';
    case 'TRANSFERRED':
      return '已转办';
    default:
      return '未知';
  }
}

// 格式化日期
function formatDate(date: string | Date | undefined): string {
  if (!date) return '-';
  return format(new Date(date), 'yyyy-MM-dd HH:mm');
}

// 检查是否超时
function isOverdue(dueDate: string | Date | undefined): boolean {
  if (!dueDate) return false;
  return isPast(new Date(dueDate));
}

// 检查是否可以处理任务
function canProcess(task: ApprovalTaskModel): boolean {
  // 这里可以添加权限检查逻辑
  return !!task.assignee;
}

// 检查是否可以认领任务
function canClaim(task: ApprovalTaskModel): boolean {
  // 这里可以添加权限检查逻辑
  return !!(task.candidateUsers || task.candidateGroups);
}

// 加载任务列表
async function loadTasks() {
  loading.value = true;
  try {
    const params: ApprovalTaskQueryParams = {
      pageNo: currentPage.value,
      pageSize: pageSize.value,
      ...searchParams,
    };

    let response;
    switch (props.type) {
      case 'pending':
        response = await getMyPendingTasks(params);
        break;
      case 'completed':
        response = await getMyCompletedTasks(params);
        break;
      case 'candidate':
        response = await getCandidateTasks(params);
        break;
      default:
        response = await getTaskList(params);
        break;
    }

    tasks.value = response.data.rows;
    total.value = response.data.total;
  } catch (error) {
    console.error('加载任务列表失败:', error);
    showError('加载任务列表失败');
  } finally {
    loading.value = false;
  }
}

// 搜索
function handleSearch() {
  currentPage.value = 1;
  loadTasks();
}

// 重置搜索
function resetSearch() {
  Object.keys(searchParams).forEach(key => {
    (searchParams as any)[key] = '';
  });
  currentPage.value = 1;
  loadTasks();
}

// 刷新列表
function refreshList() {
  loadTasks();
}

// 查看详情
function viewDetail(task: ApprovalTaskModel) {
  selectedTask.value = task;
  detailDialog.value = true;
}

// 处理任务
function processTask(task: ApprovalTaskModel, action: 'APPROVE' | 'REJECT') {
  selectedTask.value = task;
  processAction.value = action;
  processDialog.value = true;
}

// 认领任务
async function claimTask(task: ApprovalTaskModel) {
  try {
    await claimTaskApi({ taskId: task.taskId! });
    showSuccess('任务认领成功');
    refreshList();
  } catch (error) {
    console.error('认领任务失败:', error);
    showError('认领任务失败');
  }
}

// 委托任务
function delegateTask(task: ApprovalTaskModel) {
  selectedTask.value = task;
  delegateDialog.value = true;
}

// 转办任务
function transferTask(task: ApprovalTaskModel) {
  selectedTask.value = task;
  transferDialog.value = true;
}

// 页面挂载时加载数据
onMounted(() => {
  loadTasks();
});
</script>

<style scoped>
.v-card-title {
  padding: 16px 24px;
  border-bottom: 1px solid rgb(var(--v-theme-surface-variant));
}

.gap-2 {
  gap: 8px;
}
</style> 